<template>
  <div style="padding:30px;">
    <!-- <el-alert :closable="false">
      <router-view />
    </el-alert>-->
  <el-table
    v-loading="loading"
    :data="tableData"
    align="center"
    border
    style="width: 100%">
    <el-table-column
      label="ID"
      align="center"
      width="180"
        prop="id">
      <!-- <template slot-scope="scope">
  
        <span style="margin-left: 10px">{{ scope.row.id }}</span>
      </template> -->
    </el-table-column>
    <el-table-column
    align="center"
      label="部门名称"
      width="180"
      prop="name">
     
    </el-table-column>
        <el-table-column
        align="center"
      label="部门管理员"
      width="180"
       prop="person">

    </el-table-column>
        <el-table-column
        align="center"
      label="管理员电话"
      width="180"
       prop="telephone">
  
    </el-table-column>
        <!-- <el-table-column
        align="center"
      label="权限类别"
      width="100"
       prop="name">
      <template slot-scope="scope">
        <el-popover trigger="hover" placement="top">
  
          <div slot="reference" class="name-wrapper">
            <el-tag size="medium">{{ scope.row.usertype }}</el-tag>
          </div>
        </el-popover>
      </template>
    </el-table-column> -->
    <el-table-column label="操作" align="center">
      <template slot-scope="scope">
        <el-button
          size="mini"
          @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
    <v-pagination 
            @page-change="pageChange" 
            class="p"
            v-show="page"
            @page-size-change="pageSizeChange" 
            :total="total" :page-size="pageSize" 
            :layout="['total', 'prev', 'pager', 'next', 'sizer', 'jumper']">
        </v-pagination>

    <el-dialog title="修改部门信息" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="115px" class="demo-ruleForm">
      <el-form-item  label="所属分公司" prop="name">
        <vxe-select v-model="editForm.bid" class="select" placeholder="请选择">
          <vxe-option v-for="( item , i ) in coms" :key="i" :value="item.id" :label="item.name" />
        </vxe-select>
      </el-form-item>

      <el-form-item label="部门名称" prop="name">
        <el-col :span="22">
          <el-input v-model="editForm.name" :readonly="true"/>
        </el-col>
      </el-form-item>

      <el-form-item label="部门管理员" prop="person">
        <el-col :span="22">
          <el-input v-model="editForm.person" />
        </el-col>
      </el-form-item>

      <!-- <el-form-item label="密码" prop="password">
        <el-col :span="22">
          <el-input type="password" v-model="editForm.password" />
        </el-col>
      </el-form-item> -->

      <!-- 这里应该有个总公司的id的，可能是默认带了 -->
      <el-form-item label="管理员电话" prop="telephone">
        <el-col :span="22">
          <el-input v-model="editForm.telephone" />
        </el-col>
      </el-form-item>
      </el-form>
      <div v-show="fail" class="fgs">{{failc}}</div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>





  </div>
</template>

<!-- 引入组件库 -->

<script>
import { hqfgs } from "@/api/zuzhijiagou";
import { getToken, gettype, getid } from "@/utils/auth";
import axios from "axios";
import { selectdown, add_depart, get_depart } from "@/api/cid";
import request from "@/utils/request";
export default {
  name: "DepartList",
  data() {
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;

      if (regMobile.test(value)) {
        return cb();
      }

      cb(new Error("请输入合法的手机号"));
    };
    return {
      page: false,
      fail: false,
      failc: "",
      coms: [],
      // 查询到的用户信息对象
      editForm: {
        cid: parseInt(getid()),
        bid: "",
        del: 0,
        name: "",
        person: "",
        telephone: ""
      },
      editFormRules: {
        name: [{ required: true, message: "请输入部门名称", trigger: "blur" }],
        person: [
          { required: true, message: "请输入管理员姓名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        telephone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" }

          // { required: true, message: "请输入手机号", trigger: "blur" },
          // { min: 11, max: 11, message: "请输入11手机号", trigger: "blur" }
        ]
      },
      editDialogVisible: false,
      list: null,
      pm: {
        tokens: getToken(),
        page: 1,
        pageSize: 10
      },
      loading: false,
      pageIndex: 1,
      pageSize: 10,
      total: 1,

      tableData: []
    };
  },
  created() {
    this.findList();
  },
  methods: {
    selectdown() {
      var that = this;
      var p = {
        tokens: getToken()
      };
      request(`branch/selectdown`, {
        method: "get",
        headers: { "Content-Type": "application/json" },
        params: p
      })
        .then(function(response) {
          console.log(response);
          if (response.data.code == 1) {
            that.coms = response.data.object;
          } else {
            that.fail = true;
            that.failc = response.message;
          }
        })
        .catch(error => {
          this.loading = false;
          that.fail = true;
          that.failc = response.message;
          console.log(error); //异常
        });
    },
    cancel() {
      this.editDialogVisible = false;
      this.failc = "";
      this.editForm = {
        cid: parseInt(getid()),
        bid: "",
        del: 0,
        name: "",
        password: "",
        person: "",
        telephone: ""
      };
    },
    // 监听修改用户对话框的关闭事件
    findid(id) {
      var that = this;
      var p = {
        tokens: getToken()
      };
      request(`department/find/${id}`, {
        method: "get",
        headers: { "Content-Type": "application/json" },
        params: p
      })
        .then(function(response) {
          that.fail = false;
          console.log(response);
          if (response.data.code == 1) {
            that.editForm = response.data.object;
          } else {
            that.fail = true;
            that.failc = response.message;
          }
        })
        .catch(error => {
          console.log(error);
          this.loading = false;
          console.log(error); //异常
        });
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    editUserInfo() {
      var that = this;
      console.log("----", this.editForm);
      this.$refs.editFormRef.validate(async valid => {
        console.log(valid);
        if (!valid) {
          return;
        }
        if (that.editForm.bid == "") {
          that.$message.error("请选择分公司！");
          return;
        }
        var d = this.editForm;
        // 发起修改用户信息的数据请求
        request(`department/update`, {
          method: "post",
          headers: {
            "Content-Type": "application/json",
            token: getToken(),
            type: 1
          },
          data: d
        })
          .then(res => {
            console.log(res);
            that.fail = !0;
            if (res.data.code == 1) {
              that.editDialogVisible = false;
              that.$message.success("更新用户信息成功！");
              // 刷新数据列表
              that.findList();
            } else {
              that.failc = res.data.message;
              setTimeout(() => {
                that.editDialogVisible = false;
              }, 1000);
            }
          })
          .catch(e => {
            console.log(e);
            that.editDialogVisible = false;
            this.$message.error("更新用户信息失败！");
          });

        // 关闭对话框

        // 提示修改成功
      });
    },
    findList() {
      var that = this;
      var resdata = {
        tokens: getToken(),
        page: that.pageIndex,
        pageSize: that.pageSize
      };
      // 模拟后台接口
      that.loading = true;
      request(`${this.$host}department/select`, {
        method: "get",
        headers: { "Content-Type": "application/json" },
        params: resdata
      })
        .then(function(response) {
          console.log(response);
          if (response.data.code == 1) {
            that.tableData = response.data.object;
            that.page = true;
          } else if (response.data.code == -1) {
            that.$message({
              type: "error",
              message: "请重新登录！!"
            });
          } else {
            that.$message({
              type: "error",
              message: response.message
            });
          }
          console.log('response.data.total:',response.data.total)
          that.total = response.data.total;
          that.loading = false;
        })
        .catch(error => {
          that.loading = false;
          that.$message({
            type: "error",
            message: "出错了！"
          });
          console.log(error); //异常
        });
    },
    // 编辑的操作
    handleEdit(index, row) {
      this.editDialogVisible = true;
      // this.loading = true;
      this.fail = true;
      this.failc = "加载中";
      this.selectdown();
      this.findid(row.id);
      // this.$message({
      //   message: "恭喜你，这是一条成功消息",
      //   type: "success"
      // });
      console.log(index, row);
    },
    // 删除的操作
    handleDelete(index, row) {
      console.log(index, row);
      var that = this;
      this.$confirm("此操作将永久删除该分公司, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(e => {
          console.log(e);
          that.loading = true;
          request(`department/del/${row.id}`, {
            method: "get",
            headers: {
              "Content-Type": "application/json",
              token: getToken(),
              type: 1
            },
            params: ""
          })
            .then(res => {
              that.loading = false;
              if (res.data.code == 1) {
                this.$message({
                  type: "success",
                  message: res.data.message
                });
                setTimeout(() => {
                  that.findList();
                }, 300);
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message
                });
              }
              console.log(res);
            })
            .catch(e => {
              console.log(e);
            });

          // this.$message({
          //   type: 'success',
          //   message: '删除成功!'
          // });
        })
        .catch(e => {
          console.log(e);
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    pageChange(pageIndex) {
      this.pageIndex = pageIndex;
      this.findList();
      console.log(pageIndex);
    },
    pageSizeChange(pageSize) {
      this.pageIndex = 1;
      this.pageSize = pageSize;
      this.findList();
    }
    // 编辑删除的操作
  }
};
</script>

<style scoped>
.p {
  margin-top: 18px !important;
}
.sortable-ghost {
  opacity: 0.8;
  color: #fff !important;
  background: #42b983 !important;
}
.select {
  z-index: 10000;
}
.el-alert__content {
  width: 100%;
}
.fgs {
  text-align: center;
  color: red;
  font-size: 19px;
}
.icon-star {
  margin-right: 2px;
}
.drag-handler {
  width: 20px;
  height: 20px;
  cursor: pointer;
}
.show-d {
  margin-top: 15px;
}
/* .el-alert__content {
  width: 50%;
} */
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 480px;
}
.el-alert__content {
  width: 100%;
}
</style>
